package com.macro.mall.tiny.service.impl;

import com.macro.mall.tiny.common.util.JwtTokenUtil;
import com.macro.mall.tiny.dao.UmsAdminRoleRelationDao;

import com.macro.mall.tiny.mbg.mapper.UmsAdminMapper;
import com.macro.mall.tiny.mbg.model.UmsAdmin;
import com.macro.mall.tiny.mbg.model.UmsAdminExample;
import com.macro.mall.tiny.mbg.model.UmsPermission;
import com.macro.mall.tiny.service.UmsAdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author ：czx
 * @date ：Created in 2021/7/16 16:11
 * @descriptioin:
 * @modified By：
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    private static final Logger LOGGER= LoggerFactory.getLogger(UmsAdminServiceImpl.class);
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;




    @Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdminExample example=new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> adminList=adminMapper.selectByExample(example);
        if (null!=adminList && adminList.size()>0){
            return adminList.get(0);
        }
        return null;
    }

    @Override
    public List<UmsPermission> getPermissionList(Long adminId) {

        return adminRoleRelationDao.getPermissionList(adminId);
    }

    /**
     * description:后台注册
     *
     */
    @Override
    public UmsAdmin register(UmsAdmin umsAdminParm) {
        UmsAdmin umsAdmin=new UmsAdmin();
        BeanUtils.copyProperties(umsAdminParm,umsAdmin);
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setStatus(1);
        //查询是否有相同用户名的用户
        UmsAdminExample example=new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());
        List<UmsAdmin>umsAdminList= adminMapper.selectByExample(example);
        if (umsAdminList.size()>0){
            return null;
        }
        //将密码进行加密操作
        String encodePassword= passwordEncoder.encode(umsAdmin.getPassword());
        umsAdmin.setPassword(encodePassword);
        adminMapper.insert(umsAdmin);
        return umsAdmin;
    }


    /**
     * description:
     *  登录
     */
    @Override
    public String login(String username, String password) {
        String token=null;
        try {
            UserDetails userDetails=userDetailsService.loadUserByUsername(username);//获取了用户信息

            if (!passwordEncoder.matches(password,userDetails.getPassword())){//传过来的密码和数据库的密码作比对
                throw new BadCredentialsException("密码不正确");
            }
            //
            UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //自动生成密码
            token=jwtTokenUtil.generateToken(userDetails);
        } catch (UsernameNotFoundException e) {
            e.printStackTrace();
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}",e.getMessage());
        }

        return token;
    }
}

















